package com.point.business.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.point.business.database.managers.InformationManager;
import com.point.business.database.model.InformationSL;
import com.point.business.database.util.UsersMaxLimitReachedException;
import com.point.business.util.UTFUtil;

/**
 * Servlet implementation class LoginServlet
 */

public class SearchSLServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SearchSLServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/plain");
		UTFUtil.utf8(request, response);
		PrintWriter out = response.getWriter();
		int userId = -1;
		if (request.getParameter("userId") != null) {
			userId = Integer.parseInt(request.getParameter("userId"));
		} else {
			userId = (Integer) request.getAttribute("userId");
		}
		String embs = request.getParameter("embs");
		String uuid = request.getParameter("uuid");
		String procedure = request.getParameter("procedure");
		if("Сите".equals(procedure)){
			procedure = "";
		}
		String title = request.getParameter("title");
		String description = request.getParameter("description");
		String searchArchive = request.getParameter("searchArchive");
		
		JsonObject jsono = new JsonObject();
		List<InformationSL> resultSL = null;
		try {
			resultSL = InformationManager.getInstance().searchSL(userId, embs,
					uuid, procedure, title, description);
			if("on".equals(searchArchive)){
				resultSL.addAll(InformationManager.getInstance().searchSLArchive(userId, embs,
					uuid, procedure, title, description));
			}
		} catch (UsersMaxLimitReachedException e) {
			jsono.addProperty("errorMsg", e.getMessage());
			out.print(jsono);
			return;
		}

		if (!resultSL.isEmpty()) {
			Gson gson = new GsonBuilder().setPrettyPrinting().create();
			String json = gson.toJson(resultSL);
			byte[] utf8JsonString = json.getBytes("UTF8");
			String str = new String(utf8JsonString, "UTF-8");
			out.print(str);
		} else {
			jsono.addProperty("isFound", false);
			jsono.addProperty("userId", userId);
			jsono.addProperty("embs", embs);
			out.print(jsono);
		}
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
}
